<template>
  <div class="app-container">
    <el-form ref="formRef" :disabled="!editAble" :model="form" :rules="rules" label-width="110px">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="出入仓类型" prop="inOrderType">
            <dict-tag :options="inout_storehouse" :value="form.inOrderType" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="调拨单编号" prop="moveCode">
            <el-tooltip effect="dark" :content="form.moveCode">
              <div class="form-text">{{ form.moveCode }}</div>
            </el-tooltip>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="调拨名称" prop="moveName">
            <el-tooltip effect="dark" :content="form.moveName">
              <div class="form-text">{{ form.moveName }}</div>
            </el-tooltip>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="工厂" prop="factory">
            <div class="form-text">{{ form.factoryName }}</div>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="调拨原因" >
            <div class="form-text">{{ form.moveReason }}</div>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-tabs v-model="activeName" class="demo-tabs">
      <el-tab-pane label="调拨明细" name="first">
        <el-row v-if="editAble" :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="plus" @click="handleAddWhStorehouseInDetail">
              添加
            </el-button>
          </el-col>
          <el-col :span="1.5" class="top-right-btn">
            <el-button type="primary" link @click="batchSetting">批量设置调拨后库位</el-button>
          </el-col>
        </el-row>
        <el-form ref="tableForm" :model="whMoveInventoryDetailList" label-width="0">
          <el-table
            :data="whMoveInventoryDetailList"
            :row-class-name="rowWhStorehouseInDetailIndex"
            border
            maxHeight="400"
            ref="whStorehouseInDetail"
          >
            <el-table-column label="序号" align="center" prop="index" width="80" />
            <el-table-column label="物料/产品名称" prop="matName" width="150" />
            <el-table-column label="物料/产品编号" prop="matCode" width="150" />

            <el-table-column label="批次号" prop="batchNo" width="150" />
            <el-table-column label="调拨前" align="center">
              <el-table-column label="工段" prop="moveFrontWorkSectionName" width="150" />

              <el-table-column label="产线" prop="moveFrontPdcLineName" width="150" />
              <el-table-column label="工艺段" prop="moveFrontProcessSectionName" width="150" />

              <el-table-column label="线边仓编码" prop="moveFrontWorkshopName" width="150" />

              <el-table-column label="库位编码" prop="moveFrontWarehouseName" width="150" />

              <el-table-column label="库存" prop="moveFrontStockNum" width="150"></el-table-column>
            </el-table-column>

            <el-table-column label="数量" prop="moveNum" width="150">
              <template v-if="editAble" #default="scope">
                <el-form-item
                  label=""
                  :prop="`[${scope.$index}].moveNum`"
                  :rules="[
                    {
                      required: true,
                      message: '请输入数量',
                      trigger: 'blur',
                    },
                  ]"
                >
                  <el-input-number
                    v-model="scope.row.moveNum"
                    controls-position="right"
                    :min="0"
                    :max="scope.row.moveFrontStockNum"
                  >
                    <template #decrease-icon>
                      <el-icon>
                        <Minus />
                      </el-icon>
                    </template>
                    <template #increase-icon>
                      <el-icon>
                        <Plus />
                      </el-icon>
                    </template>
                  </el-input-number>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="单位" prop="packageUnit" width="150" />
            <el-table-column label="调拨后" align="center">
              <el-table-column
                label="工段"
                prop="moveAfterWorkSectionName"
                width="150"
              ></el-table-column>
              <el-table-column
                label="产线"
                prop="moveAfterPdcLineName"
                width="150"
              ></el-table-column>
              <el-table-column
                label="工艺段"
                prop="moveAfterProcessSectionName"
                width="150"
              ></el-table-column>
              <el-table-column
                label="线边仓"
                prop="moveAfterWorkshopName"
                width="150"
              ></el-table-column>
              <el-table-column
                label="库位"
                prop="moveAfterWarehouseName"
                width="150"
              ></el-table-column>
            </el-table-column>
          </el-table>
        </el-form>
      </el-tab-pane>
    </el-tabs>
    <matDialog v-model="show" @change="handleChange"></matDialog>
    <el-dialog
      title="批量设置调拨后库位"
      v-model="showSetting"
      width="700px"
      :close-on-click-modal="false"
      append-to-body
    >
      <el-form ref="settingDialog" :model="settingForm" :rules="settingRules" label-width="100px">
        <el-form-item label="工段" prop="workshopCode">
          <DeptSelect
            v-model="settingForm.workshopCode"
            type="workshop"
            :parent="form.factory"
            :key="`workshop`"
            @change="workshopChange(settingForm, '0')"
            placeholder="请选择工段"
          ></DeptSelect>
        </el-form-item>
        <el-form-item label="产线" prop="productLine">
          <DeptSelect
            v-model="settingForm.productLine"
            type="line"
            :key="`prodLine`"
            :parent="settingForm.workshopCode"
            @change="lineChange(settingForm, '0')"
            placeholder="请选择产线"
          ></DeptSelect>
        </el-form-item>
        <el-form-item label="工艺段" prop="sectionCode">
          <DeptSelect
            v-model="settingForm.sectionCode"
            type="section"
            :key="`prodSection`"
            :parent="settingForm.productLine"
            @change="sectionChange(settingForm, '0')"
            placeholder="请选择工艺段"
          ></DeptSelect>
        </el-form-item>
        <el-form-item label="线边仓" prop="storehouse">
          <StoreSelect
            v-model="settingForm.storehouse"
            :key="`storehouse`"
            :line="settingForm.productLine"
            :section="settingForm.sectionCode"
            @change="storeChange(settingForm, '0')"
            placeholder="请选择线边仓段"
            title="选择线边仓"
          ></StoreSelect>
        </el-form-item>
        <el-form-item label="库位" prop="bin">
          <BinSelect
            v-model="settingForm.bin"
            :key="`bin`"
            :parent="settingForm.storehouse"
            placeholder="请选择库位"
          ></BinSelect>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitSetting">确 定</el-button>
          <el-button @click="cancelSetting">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="warehouse">
import {
  // getMoveInventory,
  addMoveInventory,
  confirmMoveInventory,
  listMoveInventoryDetail,
  listMoveInventory,
  // delMoveInventoryDetail,
} from "@/api/warehouse/moveInventory";
import { ref, reactive, toRefs, useAttrs, getCurrentInstance, onMounted } from "vue";
import matDialog from "@/components/matDialog/matDialog.vue";
const attrs = useAttrs();
const { proxy } = getCurrentInstance();
const activeName = ref("first");
const { inout_storehouse } = proxy.useDict("inout_storehouse");
const operationTitle = ref("");
const isBatch = ref(false);
const refData = reactive({
  // 表单参数
  form: {},
  settingForm: {},
  // 表单校验
  rules: {
    moveReason: [{ required: true, message: "调拨原因不能为空", trigger: "change" }],
    moveCode: [{ required: true, message: "调拨单编号不能为空", trigger: "blur" }],
    moveName: [{ required: true, message: "调拨名称不能为空", trigger: "blur" }],
    factory: [{ required: true, message: "工厂编码不能为空", trigger: "change" }],
  },
  settingRules: {
    workshopCode: [{ required: true, message: "工段不能为空", trigger: "change" }],
    productLine: [{ required: true, message: "产线不能为空", trigger: "change" }],
    storehouse: [{ required: true, message: "线边仓不能为空", trigger: "change" }],
    bin: [{ required: true, message: "库位不能为空", trigger: "change" }],
  },
});
const { form, rules, settingForm, settingRules } = toRefs(refData);
const emit = defineEmits(["close", "setActions", "setIsActionTop"]);
const whMoveInventoryDetailList = ref([]);
// const checkedWhStorehouseInDetail = ref([]);
const formRef = ref("formRef");
const tableForm = ref("tableForm");
const show = ref(false);
const editAble = ref(false);
// const binEditAble = ref(false);
const actions = ref([
  {
    text: "取 消",
    theme: "",
    handle: () => {
      cancel();
    },
  },
  {
    text: "确 定",
    theme: "primary",
    handle: () => {
      submitForm();
    },
    loading: false,
  },
]);
const showSetting = ref(false);

// var factoryOptions = ref([]);
// var workshopOptions = ref([]);
// var lineOptions = ref([]);
// var processOptions = ref([]);
const settingDialog = ref("settingDialog");
const batchSetting = () => {
  showSetting.value = true;
};
// const selectSubData = computed(() => {
//   return checkedWhStorehouseInDetail.value.map((item) => item.index);
// });
const submitSetting = () => {
  settingDialog.value.validate((valid) => {
    if (valid) {
      whMoveInventoryDetailList.value.forEach((el) => {
        el.moveAfterWorkSection = settingForm.value.workshopCode;
        el.moveAfterPdcLine = settingForm.value.productLine;
        el.moveAfterProcessSection = settingForm.value.sectionCode;
        el.moveAfterWorkshopCode = settingForm.value.storehouse;
        el.moveAfterWarehouse = settingForm.value.bin;
      });
      showSetting.value = false;
    }
  });
};
const cancelSetting = () => {
  showSetting.value = false;
};
// 取消按钮
function cancel() {
  emit("close");
}
// function handleFactoryChange(val) {
//   settingForm.value.workshopCode = "";
//   settingForm.value.productLine = "";
//   settingForm.value.sectionCode = "";
//   whMoveInventoryDetailList.value.forEach((el) => {
//     el.moveAfterWorkSection = "";
//     el.moveAfterPdcLine = "";
//     el.moveAfterProcessSection = "";
//     el.moveAfterWorkshopCode = "";
//     el.moveAfterWarehouse = "";
//   });
// }

function workshopChange(row, type) {
  if (!type) {
    row.moveAfterPdcLine = "";
    row.moveAfterProcessSection = "";
    row.moveAfterWorkshopCode = "";
    row.moveAfterWarehouse = "";
  } else {
    row.productLine = "";
    row.sectionCode = "";
    row.storehouse = "";
    row.bin = "";
  }
}

function lineChange(row, type) {
  if (!type) {
    row.moveAfterProcessSection = "";
    row.moveAfterWorkshopCode = "";
    row.moveAfterWarehouse = "";
  } else {
    row.sectionCode = "";
    row.storehouse = "";
    row.bin = "";
  }
}
function sectionChange(row, type) {
  if (!type) {
    row.moveAfterWorkshopCode = "";
    row.moveAfterWarehouse = "";
  } else {
    row.storehouse = "";
    row.bin = "";
  }
}
function storeChange(row, type) {
  if (!type) {
    row.moveAfterWarehouse = "";
  } else {
    row.bin = "";
  }
}

// 表单重置
function reset() {
  form.value = {
    factory: "",
    inOrderType: "7",

    moveCode: "",

    moveName: "",
    moveReason: "",
    moveTime: "",
    remark: "",
    status: "",
    whMoveInventoryDetailList: [],
  };
  formRef.value.resetFields();
  whMoveInventoryDetailList.value = [];
}

/** 修改按钮操作 */
function getDetail(id,data) {
  listMoveInventory({ moveCode: id }).then((response) => {
    if (response.rows && response.rows.length) {
      form.value = response.rows[0];
      form.value.inOrderType = data.inOutType;
      getListWhStorehouseInDetail(form.value.moveCode);
    }
  });
}

/** 提交按钮 */
function submitForm() {
  if (operationTitle.value == "确认调拨") {
    proxy.$modal.confirm("是否提交确认调拨？").then(() => {
      confirmMoveInventory(form.value.id)
        .then(() => {
          proxy.$modal.msgSuccess("提交成功");
          cancel();
        })
        .catch(() => {
          proxy.$modal.msgError("提交失败，请重试");
        });
    });
  } else {
    formRef.value.validate((valid) => {
      if (valid) {
        form.value.whMoveInventoryDetailList = whMoveInventoryDetailList.value;
        // if (form.value.id) {
        //   updateInStorehouse(form.value).then((response) => {
        //     proxy.$modal.msgSuccess("编辑成功");
        //     cancel();
        //   });
        // } else {
        addMoveInventory(form.value).then(() => {
          proxy.$modal.msgSuccess("新增成功");
          cancel();
        });
        // }
      }
    });
  }
}

/** 物料调拨明细序号 */
function rowWhStorehouseInDetailIndex({ row, rowIndex }) {
  row.index = rowIndex + 1;
}
/** 物料调拨明细添加按钮操作 */
function handleAddWhStorehouseInDetail() {
  show.value = true;
}
function handleChange(val) {
  if (val.length) {
    console.log(val);

    val.forEach((el) => {
      let obj = {};
      obj.matCode = el.matCode;
      obj.matName = el.matName;
      obj.batchNo = el.batchNo;
      obj.measureUnit = el.measureUnit;
      obj.packing = el.packing;
      obj.moveFrontStockNum = el.num;
      obj.moveNum = el.num;
      // 调拨前
      obj.moveFrontWorkSection = el.workShopCode;
      obj.moveFrontPdcLine = el.lineCode;
      obj.moveFrontProcessSection = el.sectionCode;
      obj.moveFrontWorkshopCode = el.storehouseCode;
      obj.moveFrontWarehouse = el.binCode;
      obj.moveCode = form.value.moveCode;
      // 调拨后
      obj.moveAfterWorkSection = "";
      obj.moveAfterPdcLine = "";
      obj.moveAfterProcessSection = "";
      obj.moveAfterWorkshopCode = "";
      obj.moveAfterWarehouse = "";

      whMoveInventoryDetailList.value.push(obj);
    });
  }
}
/** 物料调拨明细删除按钮操作 */
// function handleDeleteWhStorehouseInDetail(row, index) {
//   proxy.$modal
//     .confirm("是否确认删除所选数据项？")
//     .then(() => {
//       if (row.id) {
//         delMoveInventoryDetail(row.id).then((res) => {
//           whMoveInventoryDetailList.value =
//             whMoveInventoryDetailList.value.filter((item) => {
//               return item.id !== row.id;
//             });
//           this.$modal.msgSuccess("删除成功");
//         });
//       } else {
//         whMoveInventoryDetailList.value.splice(index, 1);
//         this.$modal.msgSuccess("删除成功");
//       }
//     })
//     .catch(() => {});
// }
/** 复选框选中数据 */
// function handleWhStorehouseInDetailSelectionChange(selection) {
//   checkedWhStorehouseInDetail.value = selection;
// }

// function delSubTable(id) {
//   delMoveInventoryDetail(id).then((res) => {
//     proxy.$modal.msgSuccess("删除成功");
//   });
// }

function getListWhStorehouseInDetail(code) {
  listMoveInventoryDetail({ pageSize: 10000, pageNum: 1, moveCode: code }).then((res) => {
    if (isBatch.value) {
      whMoveInventoryDetailList.value.push(...res.rows);
    } else {
      whMoveInventoryDetailList.value = res.rows;
    }
  });
}

onMounted(() => {
  reset();
  const { data } = attrs;
  console.log(data);
  actions.value = [];
  editAble.value = false;
  emit("setActions", actions.value);

  if (data) {
    getDetail(data.mainTableId,data);
  }
});
</script>

<style lang="scss">
.form-text {
  width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</style>
